package cz.proks.schoolpupilbook.gwt.core;

import com.google.gwt.user.client.Cookies;

import cz.proks.schoolpupilbook.shared.Constants;
import cz.proks.schoolpupilbook.shared.domain.User;
import cz.proks.schoolpupilbook.shared.domain.User.Role;

public class CookieHelper {
	public static String asCookie(User u) {
		if (u == null)
			return "";
		
		StringBuilder sb = new StringBuilder();
		sb.append("{")
			.append(u.getId()).append(";")
			.append(u.getName()).append(";")
			.append(u.getSurname()).append(";")
			.append(u.getRole().toString()).append(";")
			.append("Login{")
				.append(u.getUsername()).append("/")
				.append(u.getPassword())
				.append("}")
			.append("}");
		return sb.toString();
	}
	
	public static User getUserFromCookie(String cookie) {
		if (cookie == null || !cookie.startsWith("{") || !cookie.endsWith("}"))
			return null;
		
		cookie = cookie.substring(1, cookie.length() - 1);
		String[] dataArray = cookie.split(";");
		
		if (dataArray == null || dataArray.length != 5)
			return null;
		
		String id = dataArray[0];
		String name = dataArray[1];
		String surname = dataArray[2];
		String role = dataArray[3];
		
		String loginObj = dataArray[4];
		if (!loginObj.startsWith("Login{") || !loginObj.endsWith("}"))
			return null;
		
		String[] loginDataArray = loginObj.substring("Login{".length(), loginObj.length()-1).split("/");
		if (loginDataArray == null || loginDataArray.length != 2)
			return null;
		
		String login = loginDataArray[0];
		String password = loginDataArray[1];
		
		return new User(id, name, surname, Role.valueOf(role), login, password);
	}		

	public static boolean isUserLogged() {
		String loggedString = Cookies.getCookie(Constants.Cookie.USER_LOGGED);
		boolean userLogged;
		
		if (loggedString == null)
			return false;
		
		 try { userLogged = Boolean.valueOf(loggedString); }
		 catch(Exception ex) { userLogged = false; }
		 		 
		 return userLogged;
	}

	public static User getLoggedUser() {
		boolean isUserLogged = isUserLogged();
		String userCookie = Cookies.getCookie(Constants.Cookie.USER);		
		User user = getUserFromCookie(userCookie);
		
		return isUserLogged ? user : null;
	}
}
